package cn.kdyzm.twofa.controller.api;

import cn.hutool.core.util.StrUtil;
import cn.kdyzm.json.util.JsonUtils;
import cn.kdyzm.twofa.entity.SysUser;
import cn.kdyzm.twofa.mapper.ISysUserMapper;
import cn.kdyzm.twofa.models.WrapperResult;
import cn.kdyzm.twofa.models.dto.CheckTwoFaReq;
import cn.kdyzm.twofa.models.dto.TwoFaSettingsSubmitReq;
import cn.kdyzm.twofa.service.ITwoFaService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author kdyzm
 * @date 2025/6/16
 */
@RestController
@RequestMapping("/2fa")
@Slf4j
@AllArgsConstructor
public class TowFaApi {

    private final ITwoFaService twoFaService;

    private final ISysUserMapper sysUserMapper;

    @PostMapping("/check_2fa_code")
    public WrapperResult<Boolean> check2faCode(CheckTwoFaReq req, @CookieValue("userId") Long userId) {
        log.info("获取到cookie：{}", userId);
        SysUser sysUser = sysUserMapper.selectById(userId);
        Boolean aBoolean = twoFaService.checkCode(sysUser.getUserName(), req.getCode());
        return WrapperResult.success(aBoolean);
    }

    @PostMapping("/2fa_settings")
    public WrapperResult<Boolean> submit(TwoFaSettingsSubmitReq req, @CookieValue("userId") Long userId) {
        log.info(JsonUtils.toPrettyString(req));
        String secretKey = twoFaService.checkFirstCode(userId, req.getCode());
        if (StrUtil.isBlank(secretKey)) {
            return WrapperResult.success(Boolean.FALSE);
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        sysUser.setTwoFaSecret(secretKey);
        sysUser.setTowFaEnabled(Boolean.TRUE);
        sysUserMapper.updateById(sysUser);
        return WrapperResult.success(Boolean.TRUE);
    }

    @PostMapping("/close_two_fa")
    public WrapperResult<Boolean> close2Fa(@CookieValue("userId") Long userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        sysUser.setTowFaEnabled(Boolean.FALSE);
        sysUserMapper.updateById(sysUser);
        return WrapperResult.success(Boolean.TRUE);
    }

}
